package com.example.demozmq.zmq;

import java.nio.charset.StandardCharsets;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.zeromq.ZMQ;

@SpringBootTest
public class ZmqClient {

    @Test
    public void testSendMessage2Server() {
        ZMQ.Context context = ZMQ.context(1);
        ZMQ.Socket socket = context.socket(ZMQ.REQ);
        // 连接服务器
        socket.connect("tcp://localhost:5555");
        // 发送消息
        String text = "你好，我是客户端。";
        byte[] bytes = text.getBytes(StandardCharsets.UTF_8);
        socket.send(bytes);
        // 等待回复
        byte[] reply = socket.recv(0);
        String response = new String(reply);
        System.out.println("接收到服务器的消息是：" + response);
    }

    public static void main(String[] args) throws InterruptedException {
        ZMQ.Context context = ZMQ.context(1);
        ZMQ.Socket socket = context.socket(ZMQ.REQ);
        // 连接服务器
        socket.connect("tcp://localhost:5555");

        for (int i = 0; i < 10000; i++) {
            // 发送消息
            String text = "你好，我是客户端。" + i;
            byte[] bytes = text.getBytes(StandardCharsets.UTF_8);
            socket.send(bytes);
            // 等待回复
            byte[] reply = socket.recv(0);
            String response = new String(reply);
            System.out.println("接收到服务器的消息是：" + response);
            Thread.sleep(5000);
        }
    }
}
